"use strict"

var gulp = require('gulp');
var gulpChanged = require('gulp-changed');
var cssMinify = require('gulp-clean-css');
var del = require('del');
var gulpDebug = require('gulp-debug');
var gulpHeader = require('gulp-header');
var gulpFilter = require('gulp-filter');
var fileinclude = require('gulp-file-include');
var processhtml = require('gulp-processhtml');
var gulpSequence = require('gulp-sequence');
var gulpSass = require('gulp-sass');
var gulpUglify = require('gulp-uglify');

var browserSync = require('browser-sync').create(), 
    bsReload = browserSync.reload;

var $CFG = require('./config');
var $CFG_STYLES = $CFG.styles, 
    $CFG_IMG = $CFG.images, 
    $CFG_JS = $CFG.scripts, 
    $CFG_HTML = $CFG.html;
    
/* ****************************************
 * Css 文件处理
 * **************************************** */
gulp.task('clean:Css', function() {
    del($CFG_STYLES.dest +'/**/*');
});
gulp.task('taskCss', function() {
    var filterArr = [
        '**/*.css', 
        '!'+ $CFG_STYLES.src +'/**/*{-min,_min,.min}.css'
    ];
    var cssFilter = gulpFilter(filterArr, { restore: true });
    
    return gulp.src([
        $CFG_STYLES.src +'/**', 
        '!'+ $CFG_STYLES.src_sass +'/', 
		'!'+ $CFG_STYLES.src_sass +'/**/*', 
		'!'+ $CFG_STYLES.src_sass +'/**/*.scss'
    ])
    .pipe(gulpChanged($CFG_STYLES.dest +'/'))
    .pipe(cssFilter)
    .pipe(cssMinify($CFG_STYLES.cssMinOptions))
    .pipe(gulpDebug({ title: 'Css打包:' }))
    .pipe(cssFilter.restore)
    .pipe(gulp.dest($CFG_STYLES.dest +'/'))
    .pipe(bsReload({ stream: true }));
});
gulp.task('taskCss:Sass', function() {
    return gulp.src($CFG_STYLES.src_sass +'/**/*.scss')
    .pipe(gulpChanged($CFG_STYLES.dest))
    .pipe(gulpSass($CFG_STYLES.sassOptions).on('error', gulpSass.logError))
	.pipe(gulpHeader('@charset "utf-8";'))
    .pipe(gulpDebug({ title: 'Compiling Sass:' }))
    .pipe(gulp.dest($CFG_STYLES.dest))
    .pipe(bsReload({ stream: true }));
});

/* ****************************************
 * Js 文件处理
 * **************************************** */
gulp.task('clean:Js', function() {
    del($CFG_JS.dest +'/**/*');
});
gulp.task('taskJs', function() {
    var filterArr = [
        '**/*.js', 
		'!'+ $CFG_JS.src +'/**/*{-min,_min,.min,.src}.js', 
       '!'+ $CFG_JS.src +'/library/jquery_plugins/layer/layer.js',
			'!'+ $CFG_JS.src +'/general.config.js',
			'!'+ $CFG_JS.src +'/library/json3.js',
			'!'+ $CFG_JS.src +'/library/jquery_plugins/jquery_select2.js'
    ];
    var filterTmp = gulpFilter(filterArr, { restore: true });

    return gulp.src([$CFG_JS.src +'/**'])
    .pipe(gulpChanged($CFG_JS.dest))
    .pipe(filterTmp)
    .pipe(gulpUglify($CFG_JS.uglifyOptions))
    .pipe(gulpDebug({ title: 'Js打包:' }))
    .pipe(filterTmp.restore)
    .pipe(gulp.dest($CFG_JS.dest))
    .pipe(bsReload({ stream: true }));
});

/* ****************************************
 * Images 文件处理（不进行图片无损、深度压缩）
 * **************************************** */
gulp.task('clean:Images', function() {
    del($CFG_IMG.dest +'/**/*');
});
gulp.task('taskImages', function() {
    return gulp.src($CFG_IMG.src +'/**/*')
    .pipe(gulpChanged($CFG_IMG.dest))
    .pipe(gulpDebug({ title: 'Images打包:' }))
    .pipe(gulp.dest($CFG_IMG.dest))
	.pipe(bsReload({ stream: true }));
});

/* ****************************************
 * html 文件处理
 * **************************************** */
gulp.task('clean:Html', function() {
	del([
	    $CFG_HTML.dest +'/**/*', 
		'!'+ $CFG_STYLES.dest +'/**/*', 
		'!'+ $CFG_JS.dest +'/**/*', 
		'!'+ $CFG_IMG.dest +'/**/*'
	]);
});
gulp.task('taskHtml', function() {
    var filterArr = [
        '**/*.html',
		'!'+ $CFG_HTML.src +'/tpl.*.html', 
		'!'+ $CFG_HTML.src +'/**/*{-min,_min,.min}.html', 
    ];
    var htmlFilter = gulpFilter(filterArr, { restore: true });

    return gulp.src([
	    $CFG_HTML.src +'/**/*.html',
	    '!'+ $CFG_HTML.src +'/tpl.*.html'
	])
    .pipe(htmlFilter)
	.pipe(gulpChanged($CFG_HTML.dest +'/html/'))
    .pipe(fileinclude({
        prefix: '@@',
        basepath: '@file'
    }))
    .pipe(processhtml())
    .pipe(gulpDebug({ title: 'Html打包:' }))
	.pipe(htmlFilter.restore)
    .pipe(gulp.dest($CFG_HTML.dest +'/html/'))
    .pipe(bsReload({ stream: true }));
});
gulp.task('taskAllHtml', function() {
    var filterArr = [
       	'**/*.html',
		'!'+ $CFG_HTML.src +'/tpl.*.html', 
		'!'+ $CFG_HTML.src +'/**/*{-min,_min,.min}.html', 
    ];
    var htmlFilter = gulpFilter(filterArr, { restore: true });

    return gulp.src([
	    $CFG_HTML.src +'/**/*.html',
	    '!'+ $CFG_HTML.src +'/tpl.*.html', 
	])
    .pipe(htmlFilter)
    .pipe(fileinclude({
        prefix: '@@',
        basepath: '@file'
    }))
    .pipe(processhtml())
    .pipe(gulpDebug({ title: 'Html打包:' }))
	.pipe(htmlFilter.restore)
    .pipe(gulp.dest($CFG_HTML.dest +'/html/'))
    .pipe(bsReload({ stream: true }));
});

/* ****************************************
 * 其他操作处理
 * **************************************** */
gulp.task('build', function(callback) {
    gulpSequence(
        ['clean:Css', 'clean:Js', 'clean:Images', 'clean:Html'], 
		'taskCss:Sass', 
        'taskCss', 
		'taskJs', 
        'taskImages', 
		'taskHtml',
        callback
    );
});

//创建本地服务器，并且实时更新页面文件
gulp.task('browser-sync', ['build'], function() {
    browserSync.init($CFG.browsersync);
});
gulp.task('default', ['browser-sync'], function() {
    gulp.watch($CFG.watch.css, ['taskCss']);
    gulp.watch($CFG.watch.sass, ['taskCss:Sass']);
    gulp.watch($CFG.watch.scripts, ['taskJs']);
    var watcherImages = gulp.watch($CFG.watch.images, ['taskImages']);
    watcherImages.on('change', function(event) {
        console.log('File: ' + event.path + ' was ' + event.type + ', running tasks...');
    });
    var watcherHtml = gulp.watch($CFG.watch.html, ['taskHtml']);
		gulp.watch($CFG.watch.commonPart,['taskAllHtml']);

    watcherHtml.on('change', function(event) {
        console.log('File: ' + event.path + ' was ' + event.type + ', running tasks...');
    });
});